package org.base23.uaa.business.controller;


import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.base23.uaa.business.service.MenuPermissionService;
import org.base23.uaa.core.domain.entity.MenuPermission;
import org.base23.uaa.core.exception.UaaExceptions;
import org.base23.web.model.Result;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/permission")
@Validated
@Tag(name = "权限管理", description = "菜单和按钮权限的CRUD操作")
public class PermissionController {

  private final MenuPermissionService menuService;

  public PermissionController(MenuPermissionService menuService) {
    this.menuService = menuService;
  }

  @GetMapping("/tree")
  @Operation(summary = "获取权限树", description = "获取所有权限的树形结构")
  public Result getPermissionTrees() {
    return Result.data(menuService.getPermissionTree());
  }

  @GetMapping("/menu/tree")
  @Operation(summary = "获取菜单权限树", description = "获取菜单类型权限的树形结构")
  public Result getMenuPermissionTrees() {
    return Result.data(menuService.getMenuPermissionTree());
  }

  @GetMapping("/button/{permissionId}")
  @Operation(summary = "获取按钮权限", description = "根据父级权限ID获取按钮类型权限")
  public Result getButtonPermission(@Parameter(description = "父级权限ID") @PathVariable("permissionId") Long permissionId) {
    return Result.data(menuService.getButtonPermissionByParentId(permissionId));
  }

  @PostMapping
  @Operation(summary = "添加权限", description = "创建新的菜单或按钮权限")
  public Result addPermission(@RequestBody MenuPermission menuPermission) {
    menuService.addMenuPermission(menuPermission);
    return Result.data(menuPermission);
  }

  @DeleteMapping("/{id}")
  @Operation(summary = "删除权限", description = "注意：当前系统禁止删除权限")
  public Result deletePermission(@Parameter(description = "权限ID") @PathVariable("id") long id) {
    throw UaaExceptions.FORBID_DELETE.exception();
  }

  @PatchMapping("/{id}")
  @Operation(summary = "更新权限", description = "修改菜单或按钮权限信息")
  public Result updatePermission(
      @Parameter(description = "权限ID") @PathVariable("id") long id,
      @RequestBody MenuPermission menuPermission) {
    menuPermission.setId(id);
    menuService.updatePermission(menuPermission);
    return Result.data(true);
  }
}
